(defun clang-alloc(&optional type)
  (interactive)
  (or type (read-from-minibuffer "Enter Type Name:"))
  (insert (format ()))
  )

(defun clang-debug()
  (interactive)
  (insert "#define INFO(msg) \\
    fprintf(stderr, \"info: %s:%s: \", __FILE__, __LINE__); \\
    fprintf(stderr, \"%s\", msg);")
  )

(defun clang-print()
  ""
  (interactive)
  (insert "printf(\"%s %s %d\\n\",__FUNCTION__,__FILE__,__LINE__);")
  )

(defun clang-valist()
  (interactive)
  (insert "#include <stdio.h>
#include <stdarg.h>

void error(char *fmt, ...)
{
  va_list args;
  va_start(args, fmt);
  fprintf(stderr, \"error: \");
  vprintf(stderr, fmt, args);
  fprintf(stderr, \"\\n\");
  va_end(args);
}")
  )

(defun lex-yacclang-token()
  (interactive)
  (insert "class   {return CLASS;}
const   {return CONST;}
public  {return PUBLIC;}
private {return PRIVATE;}
\*      {return STAR;}
\(      {return LP;}
\)      {return RP;}
\{      {return LB;}
\}      {return RB;}
\:      {return COLON;}
\.      {return DOT;}
\;      {return SEMICOLON;}
\,      {return COMMA;}
\<      {return LT;}
\>      {return GT;}
[ \t\n]+   ;
")
  )

(defun clang-token()
  (interactive)
  (insert "#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include<memory.h>


typedef enum
  {
    NONE,
    DEFINE,
    START,
    VARIABLES,
    DIGIT,
    STRING,
    LEFTCBRACKET, //[
    RIGHTCBRACKET,//]
    LEFTSBRACKET ,//{
    RIGHTSBRACKET,//}
    INCLUDE ,
    DOT,          //.
    GREAT,        //>
    LESS,         //<
    NUMBER,
    IDENTITY,
    STAR,         //*
    SEMICOLON,    //,
    LEFTPARENTHESIS,      //(
    RIGHTPARENTHESIS,     //)
    LEFTQUOTE,    //'
    SHARP,        //#
    COLON,        //:
    UNDERSCORE,   //_
    SPACE,        //
    ENTERLINE,    //\\n
    TAB,          //\\t
    PLUS,         // +
    MINUS,        // -
    DIV,          ///
    ASSIGN,        // =
    EQUAL,       // ==  
    QMARK,        //?
    SLASH,        
    VBAR,          //|
    DOLLAR,       //$
    POW,          //^
    AT,           //@
    TILDE,        //~
    AUTO,
    BREAK,
    CASE,
    CHAR,
    CONST,
    CONTINUE,
    DEFAULT,
    DO,
    DOUBLE,
    ELSE,
    ENUM,
    EXTERN,
    FLOAT,
    FOR,
    GOTO,
    IF,
    INLINE,
    INT,
    LONG,
    REGISTER,
    RESTRICT,
    RETURN,
    SHORT,
    SIGNED,
    SIZEOF,
    STATIC,
    STRUCT,
    SWITCH,
    TYPEDEF,
    UNION,
    UNSIGNED,
    VOID,
    VOLATILE,
    WHILE 
  }TreeType;

struct map
{
	char *name;
	TreeType t;
};

struct map xmap[] = {
	{\"typedef\",TYPEDEF},
	{\"include\",INCLUDE},
	{\"auto\",AUTO},
	{\"break\",BREAK},
	{\"case\",CASE},
	{\"char\",CHAR},
	{\"const\",CONST},
	{\"continue\",CONTINUE},
	{\"default\",DEFAULT},
	{\"do\",DO},
	{\"double\",DOUBLE},
	{\"else\",ELSE},
	{\"enum\",ENUM},
	{\"extern\",EXTERN},
	{\"float\",FLOAT},
	{\"for\",FOR},
	{\"goto\",GOTO},
	{\"if\",IF},
	{\"inline\",INLINE},
	{\"int\",INT},
	{\"long\",LONG},
	{\"register\",REGISTER},
	{\"restrict\",RESTRICT},
	{\"return\",RETURN},
	{\"short\",SHORT},
	{\"signed\",SIGNED},
	{\"sizeof\",SIZEOF},
	{\"static\",STATIC},
	{\"struct\",STRUCT},
	{\"switch\",SWITCH},
	{\"typedef\",TYPEDEF},
	{\"union\",UNION},
	{\"unsigned\",UNSIGNED},
	{\"void\",VOID},
	{\"volatile\",VOLATILE},
	{\"while \",WHILE },
	{\"[\",    LEFTCBRACKET},
	{\"]\",    RIGHTCBRACKET},
	{\"{\",    LEFTSBRACKET },
	{\"}\",    RIGHTSBRACKET},
	{\".\",    DOT},
	{\">\",    GREAT},
	{\"<\",    LESS},
	{\"*\",    STAR},
	{\",\",    SEMICOLON},
	{\"(\",    LEFTPARENTHESIS},
	{\")\",    RIGHTPARENTHESIS},
	{\"'\",    LEFTQUOTE},
	{\"#\",    SHARP},
	{\":\",    COLON},
	{\"_\",    UNDERSCORE},
	{\" \",    SPACE},
	{\"\\n\",    ENTERLINE},
	{\"\\t\",    TAB},
	{\"+\",    PLUS},
	{\"-\",    MINUS},
	{\"\",    DIV},
	{\"=\",    ASSIGN},
	{\"==\",   EQUAL},  
	{\"?\",    QMARK},
	{\"\\\\\",    SLASH},
	{\"|\",    VBAR},
	{\"$\",    DOLLAR},
	{\"^\",    POW},
	{\"@\",    AT},
	{\"~\",    TILDE}
};

int xmapLength = sizeof(xmap)/sizeof(xmap[0]);

typedef struct token
{
  char name[40];
  TreeType t;
}Token;

Token tokens[100000];

int strlen_test(char *p)
{
  int i = 0;
  char *pt = p;

  for(;*pt != '\\0';pt++)
    {
      i++;
    }
  return i;
}


Token * makeToken_test(char *p,TreeType t)
{
  char *pt = p;
  int index = 0;
  Token *token = (Token *)malloc(sizeof(Token));
  memset(token,0,sizeof(Token));

  if(strlen_test(p)<40)
    {
      for(;*pt != '\\0';pt++)
        {
          token -> name[index++] = *pt; 
        }
      token -> name[index] = '\\0'; 
    }
  token -> t = t;
  return token;
}

TreeType Get_Tree_Type_Test(char *p)
{
  int i = 0;
  for(i = 0;i<xmapLength;i++)
    {
      if(strcmp(xmap[i].name,p) == 0) 
        {
          return xmap[i].t;
        }
    }
  return NONE;
}

void push_token()
{

}

#if 0
#define TokenArrayTestMain main
#endif

int TokenArrayTestMain(int argc,char **argv)
{
  Token t[1000];//Token Queue
  char *p = \"typedef\";

  // Token *pToken = makeToken_test(p,IDENTITY);
  printf(\"%d\\n\",Get_Tree_Type_Test(p));
  
  return 0;
}
")
  )

(defun clang-copyfile()
  (interactive)
  (insert "#include <stdio.h>
#include <fcntl.h>
#include \"syscalls.h\"
#define PERMS 0666 /* RW for owner, group, others */
void error(char *, ...);
/* cp: copy f1 to f2 */
main(int argc, char *argv[])
{
  int f1, f2, n;
  char buf[BUFSIZ];
  if (argc != 3)
    error(\"Usage: cp from to\");
  if ((f1 = open(argv[1], O_RDONLY, 0)) == -1)
    error(\"cp: can't open %s\", argv[1]);
  if ((f2 = creat(argv[2], PERMS)) == -1)
    error(\"cp: can't create %s, mode %03o\",
          argv[2], PERMS);
  while ((n = read(f1, buf, BUFSIZ)) > 0)
    if (write(f2, buf, n) != n)
      error(\"cp: write error on file %s\", argv[2]);
  return 0;
}")
  )

(defun linux-popen()
  (interactive)
  (insert "FILE *fp;
  int status;
  char path[1035];

  /* Open the command for reading. */
  fp = popen(\"/bin/ls /etc/\", \"r\");
  if (fp == NULL) {
    printf(\"Failed to run command\\n\" );
    exit;
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path)-1, fp) != NULL) {
    printf(\"%s\", path);
  }

  /* close */
  pclose(fp);

///////////////////////////////////////////
  #include <stdio.h> 
#include <unistd.h> 
 
int main () 
{
   FILE* stream = popen (\"sort\", \"w\"); 
   fprintf (stream, \"This is a test.\\n\"); 
   fprintf (stream, \"Hello, world.\\n\"); 
   fprintf (stream, \"My dog has fleas.\\n\"); 
   fprintf (stream, \"This program is great.\\n\"); 
   fprintf (stream, \"One fish, two fish.\\n\"); 
   return pclose (stream); 
} 
")
  )

(defun linux-signal()
  (interactive)
  (insert "#include <signal.h> 
#include <stdio.h> 
#include <string.h> 
#include <sys/types.h> 
#include <unistd.h> 
 
sig_atomic_t sigusr1_count = 0; 
 
void handler (int signal_number) 
{
  ++sigusr1_count; 
} 
 
  struct sigaction sa; 
  memset (&sa, 0, sizeof  (sa)); 
  sa.sa_handler = &handler; 
  sigaction (SIGUSR1, &sa, NULL); 
 
  /* Do some lengthy  stuff here. */ 
  /*  ... */ 
 
  printf (\"SIGUSR1 was raised %d times\\n\", sigusr1_count);

/*
static void
onintr(int sig GCC_UNUSED)
{
    got_intr = 1;
    done(EXIT_FAILURE);
}
if (signal(SIGINT, SIG_IGN) != SIG_IGN)
   signal(SIGINT, onintr);
*/

")
  )


(defun linux-getopt()
  (interactive)
  (insert "#include <getopt.h>
//optarg is arg
//a: means \"-a asdf\" has optarg
while ((c = getopt(argc, argv, \":af:hv\")) != -1)
{
  switch (c)
  {
    case 'a':
    do_all = 1;
    break;

    case 'f':
    myfile = optarg;
    break;

    case 'h':
    do_help = 1;
    break;

    case 'v':
    do_verbose = 1;
    break;
 }
}
")
  )

(defun linux-getoptlong()
  (interactive)
  (insert "#include <stdio.h>
#include <unistd.h>
#include <getopt.h>

int main(int argc, char *argv[])
{
  int opt;

  struct option longopts[] = {
    {\"initialize\", 0, NULL, 'i'},
    {\"file\", 1, NULL, 'f'},
    {\"list\", 0, NULL, 'l'},
    {\"restart\", 0, NULL, 'r'},
    {0,0,0,0}};
  while((opt = getopt_long(argc, argv, \"if:lr\", longopts, NULL)) != -1) {
    switch(opt) {
    case 'i':
    case 'l':
    case 'r':
      printf(\"option: %c\\n\", opt);
      break;
    case 'f':
      printf(\"filename: %s\\n\", optarg);
      break;
    case ':':
      printf(\"option needs a value\\n\");
      break;
    case '?':
      printf(\"unknown option: %c\\n\", optopt);
    break;
    }
  }
  for(; optind < argc; optind++)
    printf(\"argument: %s\\n\", argv[optind]);
  exit(0);
}
")
  )

(defun linux-fork()
  (interactive)
  (insert "#include <stdio.h> 
#include <sys/types.h> 
#include <unistd.h> 
 
int main () 
{
 pid_t child_pid; 
 
 printf (\"the main program process ID is %d\\n\", (int) getpid()); 
 
 child_pid = fork () ; 
 if (child_pid != 0) {
    printf (\"this is the parent process, with id %d\\n\", (int) getpid ()); 
    printf (\"the child's process ID is %d\\n\",(int) child_pid ); 
} 
 else 
   printf (\"this is the child process, with id %d\\n\", (int) getpid ()); 
 
 return 0; 
} 
")
  )

(defun linux-log()
  (interactive)
  (insert "#include <stdio.h>
#include <unistd.h>
#include <syslog.h>

int main(void) {

 openlog(\"slog\", LOG_PID|LOG_CONS, LOG_USER);
 syslog(LOG_INFO, \"A different kind of Hello world ... \");
 closelog();

 return 0;
}")
  )

(defun linux-pthread-create()
  (interactive)
  (insert "#include <pthread.h> 
#include <stdio.h> 
 
/* Parameters to print_function. */ 
 
struct char_print_parms 
{
 /* The character to print.*/ 
 char character; 
 /* The number of times to print it.  */ 
 int count; 
}; 
 
/* Prints a number of characters to stderr, as given by PARAMETERS, 
   which is a pointer to a struct char_print_parms. */ 
 
void* char_print (void* parameters) 
{
    /* Cast the cookie pointer to the right type.  */ 
    struct char_print_parms*  p = (struct char_print_parms*) parameters; 
    int i; 
 
    for (i = 0; i < p->count; ++i) 
      fputc (p->character,stderr); 
    return NULL; 
} 
 
/* The main program. */ 
 
int main () 
{
 pthread_t thread1_id; 
  pthread_t  thread2_id; 
  struct  char_print_parms  thread1_args; 
  struct  char_print_parms  thread2_args; 
 
  /*  Create  a  new  thread  to  print  30,000  'x's.  */ 
  thread1_args.character  =  'x'; 
  thread1_args.count  =  30000; 
  pthread_create  (&thread1_id,  NULL,  &char_print,  &thread1_args); 
 
  /*  Create  a  new  thread  to  print  20,000  o's.  */ 
  thread2_args.character  =  'o'; 
  thread2_args.count  =  20000; 
  pthread_create  (&thread2_id,  NULL,  &char_print,  &thread2_args); 
 
  return  0; 
} 
")
  )

(defun linux-sigchild()
  (interactive)
  (insert "#include <signal.h> 
#include <string.h> 
#include <sys/types.h> 
#include <sys/wait.h> 
 
sig_atomic_t child_exit_status; 
 
void clean_up_child_process (int signal_number) 
{
  /* Clean up the child process.  */ 
  int status; 
  wait (&status); 
  /* Store its exit status in a global variable.  */ 
  child_exit_status = status; 
} 
 
int main () 
{
  /* Handle SIGCHLD by calling clean_up_child_process.  */ 
  struct sigaction sigchld_action; 
  memset (&sigchld_action, 0, sizeof (sigchld_action)); 
  sigchld_action.sa_handler = &clean_up_child_process; 
  sigaction (SIGCHLD, &sigchld_action, NULL); 
 
  /* Now do things, including forking a child process.  */ 
  /* ...  */ 
 
 return 0; 
} 
")
  )

(defun linux-regex()
  (interactive)
  (insert "
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <regex.h>

int main(int argc,char **argv)
{

  regex_t regex;
  int reti;
  char msgbuf[100];

  /* Compile regular expression */
  reti = regcomp(&regex, \"^a[[:alnum:]]\", 0);
  if( reti ){ fprintf(stderr, \"Could not compile regex\\n\"); exit(1); }

  /* Execute regular expression */
  reti = regexec(&regex, \"abc\", 0, NULL, 0);
  if( !reti ){
    puts(\"Match\");
  }
  else if( reti == REG_NOMATCH ){
    puts(\"No match\");
  }
  else{
    regerror(reti, &regex, msgbuf, sizeof(msgbuf));
    fprintf(stderr, \"Regex match failed: %s\\n\", msgbuf);
    exit(1);
  }

  /* Free compiled regular expression if you want to use the regex_t again */
  regfree(&regex);
  return 0;
}
")
  )

(defun linux-fopen()
  (interactive)
  (insert "
    FILE *input_file=NULL;
    if (input_file == 0)
    {
	input_file = fopen(input_file_name, \"r\");
	if (input_file == 0)
	    open_error(input_file_name);
    }

//mkstemp
    int fd;
    char *name;
    FILE* result;

    fd = mkstemp(name);
    if (fd >= 0)
    {
        result = fdopen(fd, \"w+\");
    }

")
  )

(defun linux-floppy()
  (interactive)
  (insert "#include <sys/types.h> /* unistd.h needs this */
#include <unistd.h>    /* contains read/write */
#include <fcntl.h>

int main()
{
        char boot_buf[512];
        int floppy_desc, file_desc;
 
        
        file_desc = open(\"./boot\", O_RDONLY);
        read(file_desc, boot_buf, 510);
        close(file_desc);
        
        boot_buf[510] = 0x55;
        boot_buf[511] = 0xaa;

        floppy_desc = open(\"/dev/fd0\", O_RDWR);
        lseek(floppy_desc, 0, SEEK_CUR);
        write(floppy_desc, boot_buf, 512);
        close(floppy_desc);
}
")
  )

(defun linux-mmap()
  (interactive)
  (insert "#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <elf.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int size = 512;

int main(int argc,char **argv)
{
  int fd1,fd2;

  int i; 

  void *file1,*file2;

  fd1 = open(\"boot.bin\",O_RDONLY);
  fd2 = open(\"boot.img\",O_RDWR);


  if(fd1 ==  0)  
    {
      printf(\"Open File Error!!!\");
      exit(1);
    }

  if(fd2 ==  0)  
    {
      printf(\"Open File Error!!!\");
      exit(1);
    }


  file1 = mmap(NULL
               ,size
               ,PROT_READ
               ,MAP_SHARED
               ,fd1
               ,0);

  file2 = mmap(NULL
               ,size
               ,PROT_WRITE
               ,MAP_SHARED
               ,fd2
               ,0);

  if(file1 < 0 )  
    {
      printf(\"map fail!!!!\");
      exit(1);
    }

  if(file2 < 0 )  
    {
      printf(\"map fail!!!!\");
      exit(1);
    }

  char *p1 = (char *)file1;
  char *p2 = (char *)file2;

  for(i = 0;i<size;i++)
    {
      *p2 = *p1;
      p1++;
      p2++;
    }

  munmap(file1,size);
  munmap(file2,size);


  return 0;
}
")
  )
   
(defun linux-libpng()
  (interactive)
  (insert "/*
 * Copyright 2002-2010 Guillaume Cottenceau.
 *
 * This software may be freely redistributed under the terms
 * of the X11 license.
 *
 */

/*gcc -Wall -gdwarf-2 -g3 libpngTest.c -o libpngTest -lm -DFILEIO -I/c/software/libpng/include -L/c/software/libpng/lib/ -lpng15

copy libpng.so to /usr/lib*/

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

#define PNG_DEBUG 3
#include <png.h>

void abort_(const char * s, ...)
{
        va_list args;
        va_start(args, s);
        vfprintf(stderr, s, args);
        fprintf(stderr, \"\\n\");
        va_end(args);
        abort();
}

int x, y;

int width, height;
png_byte color_type;
png_byte bit_depth;

png_structp png_ptr;
png_infop info_ptr;
int number_of_passes;
png_bytep * row_pointers;

void read_png_file(char* file_name)
{
        char header[8];    // 8 is the maximum size that can be checked

        /* open file and test for it being a png */
        FILE *fp = fopen(file_name, \"rb\");
        if (!fp)
                abort_(\"[read_png_file] File %s could not be opened for reading\", file_name);
        fread(header, 1, 8, fp);
        if (png_sig_cmp(header, 0, 8))
                abort_(\"[read_png_file] File %s is not recognized as a PNG file\", file_name);


        /* initialize stuff */
        png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

        if (!png_ptr)
                abort_(\"[read_png_file] png_create_read_struct failed\");

        info_ptr = png_create_info_struct(png_ptr);
        if (!info_ptr)
                abort_(\"[read_png_file] png_create_info_struct failed\");

        if (setjmp(png_jmpbuf(png_ptr)))
                abort_(\"[read_png_file] Error during init_io\");

        png_init_io(png_ptr, fp);
        png_set_sig_bytes(png_ptr, 8);

        png_read_info(png_ptr, info_ptr);

        width = png_get_image_width(png_ptr, info_ptr);
        height = png_get_image_height(png_ptr, info_ptr);
        color_type = png_get_color_type(png_ptr, info_ptr);
        bit_depth = png_get_bit_depth(png_ptr, info_ptr);

        number_of_passes = png_set_interlace_handling(png_ptr);
        png_read_update_info(png_ptr, info_ptr);


        /* read file */
        if (setjmp(png_jmpbuf(png_ptr)))
                abort_(\"[read_png_file] Error during read_image\");

        row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);
        for (y=0; y<height; y++)
                row_pointers[y] = (png_byte*) malloc(png_get_rowbytes(png_ptr,info_ptr));

        png_read_image(png_ptr, row_pointers);

        fclose(fp);
}


void write_png_file(char* file_name)
{
        /* create file */
        FILE *fp = fopen(file_name, \"wb\");
        if (!fp)
                abort_(\"[write_png_file] File %s could not be opened for writing\", file_name);


        /* initialize stuff */
        png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

        if (!png_ptr)
                abort_(\"[write_png_file] png_create_write_struct failed\");

        info_ptr = png_create_info_struct(png_ptr);
        if (!info_ptr)
                abort_(\"[write_png_file] png_create_info_struct failed\");

        if (setjmp(png_jmpbuf(png_ptr)))
                abort_(\"[write_png_file] Error during init_io\");

        png_init_io(png_ptr, fp);


        /* write header */
        if (setjmp(png_jmpbuf(png_ptr)))
                abort_(\"[write_png_file] Error during writing header\");

        png_set_IHDR(png_ptr, info_ptr, width, height,
                     bit_depth, color_type, PNG_INTERLACE_NONE,
                     PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

        png_write_info(png_ptr, info_ptr);


        /* write bytes */
        if (setjmp(png_jmpbuf(png_ptr)))
                abort_(\"[write_png_file] Error during writing bytes\");

        png_write_image(png_ptr, row_pointers);


        /* end write */
        if (setjmp(png_jmpbuf(png_ptr)))
                abort_(\"[write_png_file] Error during end of write\");

        png_write_end(png_ptr, NULL);

        /* cleanup heap allocation */
        for (y=0; y<height; y++)
                free(row_pointers[y]);
        free(row_pointers);

        fclose(fp);
}


void process_file(void)
{
        if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_RGB)
                abort_(\"[process_file] input file is PNG_COLOR_TYPE_RGB but must be PNG_COLOR_TYPE_RGBA \"
                       \"(lacks the alpha channel)\");

        if (png_get_color_type(png_ptr, info_ptr) != PNG_COLOR_TYPE_RGBA)
                abort_(\"[process_file] color_type of input file must be PNG_COLOR_TYPE_RGBA (%d) (is %d)\",
                       PNG_COLOR_TYPE_RGBA, png_get_color_type(png_ptr, info_ptr));

        for (y=0; y<height; y++) {
                png_byte* row = row_pointers[y];
                for (x=0; x<width; x++) {
                        png_byte* ptr = &(row[x*4]);
                        printf(\"Pixel at position [ %d - %d ] has RGBA values: %d - %d - %d - %d\\n\",
                               x, y, ptr[0], ptr[1], ptr[2], ptr[3]);

                        /* set red value to 0 and green value to the blue one */
                        ptr[0] = 0;
                        ptr[1] = ptr[2];
                }
        }
}


int main(int argc, char **argv)
{
        if (argc != 3)
                abort_(\"Usage: program_name <file_in> <file_out>\");

        read_png_file(argv[1]);
        process_file();
        write_png_file(argv[2]);

        return 0;
}
")
  )

(defun linux-endian()
  (interactive)
  (insert "#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
  union {
    short   s;
    char    c[sizeof(short)];
  } un;

  un.s = 0x0102;

  if (sizeof(short) == 2) {
    if (un.c[0] == 1 && un.c[1] == 2)
      printf(\"big-endian\\n\");
    else if (un.c[0] == 2 && un.c[1] == 1)
      printf(\"little-endian\\n\");
    else
      printf(\"unknown\\n\");
  } else
    printf(\"sizeof(short) = %d\\n\", sizeof(short));

  exit(0);
}
")
  )

(defun linux-chmod()
  (interactive)
  (insert "#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int
main(void)
{
     struct stat      statbuf;

     /* turn on set-group-ID and turn off group-execute */

     if (stat(\"foo\", &statbuf) < 0)
         printf(\"stat error for foo\");
     if (chmod(\"foo\", (statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0)
         printf(\"chmod error for foo\");

     /* set absolute mode to \"rw-r--r--\" */

     if (chmod(\"bar\", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0)
         printf(\"chmod error for bar\");

     exit(0);
}
")
  )

(defun linux-ssh-timeout()
  ""
  (interactive)
  (insert "#In Linux, /etc/ssh/sshd_config 
ClientAliveInterval 30
TCPKeepAlive yes 
ClientAliveCountMax 99999

sudo service sshd restart

ssh -o ServerAliveInterval=100 user@example.com
")
  )

(defun linux-command-chmod()
  (interactive)
  (insert "chmod a+x my_program")
  )

(defun linux-mysql()
  (interactive)
  (insert "#include <my_global.h>
#include <mysql.h>

#pragma comment(lib,\"libmysql.lib\")
#pragma comment(lib,\"mysqlclient.lib\")

//int main(int argc, char **argv)
//{
//  printf(\"MySQL client version: %s\\n\", mysql_get_client_info());
//}

void createTable(MYSQL *conn)
{
	mysql_query(conn, \"CREATE TABLE writers(name VARCHAR(25))\");

	mysql_query(conn, \"INSERT INTO writers VALUES('Leo Tolstoy')\");
	mysql_query(conn, \"INSERT INTO writers VALUES('Jack London')\");
	mysql_query(conn, \"INSERT INTO writers VALUES('Honore de Balzac')\");
	mysql_query(conn, \"INSERT INTO writers VALUES('Lion Feuchtwanger')\");
	mysql_query(conn, \"INSERT INTO writers VALUES('Emile Zola')\");
}

void getTable(MYSQL *conn)
{
	MYSQL_RES *result;
	MYSQL_ROW row;
	int num_fields;
	int i;

	mysql_query(conn, \"SELECT * FROM writers\");
	result = mysql_store_result(conn);

	num_fields = mysql_num_fields(result);

	while ((row = mysql_fetch_row(result)))
	{
		for(i = 0; i < num_fields; i++)
		{
			printf(\"%s \", row[i] ? row[i] : \"NULL\");
		}
		printf(\"\\n\");
	}

	mysql_free_result(result);

}

int main(int argc, char **argv)
{

	MYSQL *conn;

	conn = mysql_init(NULL);

	if (conn == NULL) {
		printf(\"Error %u: %s\\n\", mysql_errno(conn), mysql_error(conn));
		return 1;
	}

	if (mysql_real_connect(conn, \"localhost\", \"root\", 
		\"123456\", \"testdb\", 0, NULL, 0) == NULL) {
			printf(\"Error %u: %s\\n\", mysql_errno(conn), mysql_error(conn));
			//exit(1);
			return 1;
	}

	//createTable(conn);
	getTable(conn);

	mysql_close(conn);

}")
  )

(defun linux-stat()
  (interactive)
  (insert "#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
  struct stat sb;

/*   if (argc != 2) { */
/*     fprintf(stderr, \"Usage: %s <pathname>\\n\", argv[0]); */
/*     exit(EXIT_FAILURE); */
/*   } */

  if (stat(\"/root/.emacs\", &sb) == -1) {
    perror(\"stat\");
    exit(EXIT_FAILURE);
  }

  printf(\"File type:                \");

  switch (sb.st_mode & S_IFMT) {
  case S_IFBLK:  printf(\"block device\\n\");            break;
  case S_IFCHR:  printf(\"character device\\n\");        break;
  case S_IFDIR:  printf(\"directory\\n\");               break;
  case S_IFIFO:  printf(\"FIFO/pipe\\n\");               break;
  case S_IFLNK:  printf(\"symlink\\n\");                 break;
  case S_IFREG:  printf(\"regular file\\n\");            break;
  case S_IFSOCK: printf(\"socket\\n\");                  break;
  default:       printf(\"unknown?\\n\");                break;
  }

  printf(\"I-node number:            %ld\\n\", (long) sb.st_ino);

  printf(\"Mode:                     %lo (octal)\\n\",
         (unsigned long) sb.st_mode);

  printf(\"Link count:               %ld\\n\", (long) sb.st_nlink);
  printf(\"Ownership:                UID=%ld   GID=%ld\\n\",
         (long) sb.st_uid, (long) sb.st_gid);

  printf(\"Preferred I/O block size: %ld bytes\\n\",
         (long) sb.st_blksize);
  printf(\"File size:                %lld bytes\\n\",
         (long long) sb.st_size);
  printf(\"Blocks allocated:         %lld\\n\",
         (long long) sb.st_blocks);

  printf(\"Last status change:       %s\", ctime(&sb.st_ctime));
  printf(\"Last file access:         %s\", ctime(&sb.st_atime));
  printf(\"Last file modification:   %s\", ctime(&sb.st_mtime));

  exit(EXIT_SUCCESS);
}
")
  )

(defun linux-chown()
  (interactive)
  (insert "#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main(int argc, char *argv[])
{
  uid_t uid;
  struct passwd *pwd;
  char *endptr;

  if (argc != 3 || argv[1][0] == '\\0') {
    fprintf(stderr, \"%s <owner> <file>\\n\", argv[0]);
    exit(EXIT_FAILURE);
  }

  uid = strtol(argv[1], &endptr, 10);  /* Allow a numeric string */

  if (*endptr != '\\0') {         /* Was not pure numeric string */
    pwd = getpwnam(argv[1]);   /* Try getting UID for username */
    if (pwd == NULL) {
      perror(\"getpwnam\");
      exit(EXIT_FAILURE);
    }

    uid = pwd->pw_uid;
  }

  if (chown(argv[2], uid, -1) == -1) {
    perror(\"chown\");
    exit(EXIT_FAILURE);
  }

  exit(EXIT_SUCCESS);
}")
  )

(defun linux-read-write()
  (interactive)
  (insert "#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
  char block[1024];
  int in, out;
  int nread;
  in = open(\"file.in\", O_RDONLY);
  out = open(\"file.out\", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
  while((nread = read(in,block,sizeof(block))) > 0)
    write(out,block,nread);
  exit(0);
}

#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
  char c;
  int in, out;
  in = open(\"file.in\", O_RDONLY);
  out = open(\"file.out\", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
  while(read(in,&c,1) == 1)
    write(out,&c,1);
  exit(0);
}")
  )

(defun linux-console-readwrite()
  (interactive)
  (insert "#include <unistd.h>
#include <stdlib.h>
int main()
{
  char buffer[128];
  int nread;
  nread = read(0, buffer, 128);
  if (nread == -1)
    write(2, \"A read error has occurred\\n\", 26);
  if ((write(1,buffer,nread)) != nread)
    write(2, \"A write error has occurred\\n\",27);
  exit(0);
}
")
  )

(defun linux-dir()
  (interactive)
  (insert "#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>

void printdir(char *dir, int depth)
{
  DIR *dp;
  struct dirent *entry;
  struct stat statbuf;
  if((dp = opendir(dir)) == NULL) {
    fprintf(stderr,\"cannot open directory: %s\\n\", dir);
    return;
  }
  chdir(dir);
  while((entry = readdir(dp)) != NULL) {
    lstat(entry->d_name,&statbuf);
    if(S_ISDIR(statbuf.st_mode)) {
      /* Found a directory, but ignore . and .. */
      if(strcmp(\".\",entry->d_name) == 0 ||
         strcmp(\"..\",entry->d_name) == 0)
        continue;
      printf(\"%*s%s/\\n\",depth,\"\",entry->d_name);
      /* Recurse at a new indent level */
      printdir(entry->d_name,depth+4);
    }
    else printf(\"%*s%s\\n\",depth,\"\",entry->d_name);
  }
  chdir(\"..\");
  closedir(dp);
}


int main()
{
  printf(\"Directory scan of .:\\n\");
  printdir(\"D:\\\\workspace\\\\test\\\\general\",0);
  printf(\"done.\\n\");
  exit(0);
}


/*
  in the 32 bit little endian, what is the output of following
  #include <stdio.h>
  int main()
  {
    long long a = 1, b = 2, c = 3;
    printf(\"%d %d %d\\n\", a, b, c);
    return 0;
  }
 */
")
  )

(defun linux-system()
  (interactive)
  (insert "#include <stdlib.h>
#include <stdio.h>
int main()
{
  printf(\"Running ps with system\\n\");
  system(\"ps -ax&\"); //run it background
  printf(\"Done.\\n\");
  exit(0);
}")
  )

(defun linux-command-openwrt()
  (interactive)
  (insert "make menuconfig
make V=99
fdisk -l
dd if=/mnt/openwrt.image of=/dev/sda bs=1M count=100")
  )

(defun linux-command-ps()
  (interactive)
  (insert "ps -af
ps -ax")
  )
   
(defun linux-gtk()
  (interactive)
  (insert "#include <gtk/gtk.h>

int main (int argc,
          char *argv[])
{
  GtkWidget *window;

  /* Initialize GTK+ and all of its supporting libraries. */
  gtk_init (&argc, &argv);

  /* Create a new window, give it a title and display it to the user. */
  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (window), \"GTK Test\");
  gtk_widget_show (window);

  /* Hand control over to the main loop. */
  gtk_main ();
  return 0;
}
")
  )

(defun linux-gtk-label()
  (interactive)
  (insert "GtkWidget *label;
  label = gtk_label_new (\"Button1\");
  gtk_label_set_selectable (GTK_LABEL (label), TRUE);

  /* Add the label as a child widget of the window. */
  gtk_container_add (GTK_CONTAINER (window), label);
  gtk_widget_show_all (window);
")
  )

(defun linux-userid()
  (interactive)
  (insert "void UserIDAndGroupID()
{
  printf(\"***** getuid/geteuid and getgid/getegid test\\n\");
  printf(\"uid =  %d,gid =  %d\\n\",getuid(),getgid());
  printf(\"euid = %d,egid = %d\\n\",geteuid(),getegid());
  printf(\"***** end\\n\");
}
")
  )

(defun linux-phoneme()
  (interactive)
  (insert "
#cd /c/openwrt/phoneme_advanced-mr2-dev-b167/cdc/build/linux-mips-openwrt

#!/bin/sh
make \\
J2ME_CLASSLIB=foundation \\
CVM_JIT=true \\
CVM_OPTIMIZED=true \\
CVM_BUILD_SUBDIR_NAME=cdclang-fp \\
CVM_JAVA_TOOLS_PREFIX=/opt/j2sdk1.4.2_18/bin/ \\
CVM_TARGET_TOOLS_PREFIX=/c/openwrt/openwrt-na9xx-r25875-20120920/staging_dir/toolchain-mipsel_r2_gcclang-linaro_uClibclang-0.9.32/bin/mipsel-openwrt-linux-uclibclang-

option:
CVM_PRELOAD_LIB=true \\

modify following files
./cdc/build/share/defs_zoneinfo.mk
TZFILE = \
    africa antarctica asia australasia europe northamerica \
    pacificnew southamerica systemv backward \
    etcetera solar87 solar88 solar89 systemv
")
  )

(defun linux-phoneme-fedora10()
  (interactive)
  (insert "#!/bin/sh
make \\
J2ME_CLASSLIB=foundation \\
CVM_JIT=true \\
CVM_OPTIMIZED=true \\
CVM_PRELOAD_LIB=true \\
CVM_BUILD_SUBDIR_NAME=cdclang-fp \\
CVM_TARGET_TOOLS_PREFIX=/c/openwrt/openwrt-na9xx-r25875-20120920/staging_dir/toolchain-mipsel_r2_gcclang-linaro_uClibclang-0.9.32/bin/mipsel-openwrt-linux-uclibclang-\\
")
  )

(defun linux-openssh()
  (interactive)
  (insert "export CC=/c/openwrt/openwrt-na9xx-r25875-20120920/staging_dir/toolchain-mipsel_r2_gcclang-linaro_uClibclang-0.9.32/bin/mipsel-openwrt-linux-uclibclang-gcc

#zlib
./configure --prefix/path/to/output

#cross compile openssl
$ cd  /work/ssh/source/openssl-0.9.8e
$ ./Configure --prefix=/work/ssh/install/openssl-0.9.8e  os/compiler:arm-none-linux-gnueabi-gcc

#with
$./configure --with-libs --with-zlib=/c/openwrt/software/zip/ --with-ssl-dir=/c/openwrt/software/openssl-0.9.8e/ --host=arm-none-linux-gnueabi

#  ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key
")
  )
(defun perl-main-full()
  (interactive)
  (insert "#!/usr/bin/perl -w
use warnings;
use diagnostics;
#perl -Mdiagnostics ./my_program

print \"\";")
  )

(defun perl-main()
  (interactive)
  (insert "#!/usr/bin/perl

print \"\"")
  )

(defun perl-string-filter()
  (interactive)
  (insert "#!/usr/bin/perl
@lines = 'perldoc -u -f atan2';
foreach (@lines) {
s/\\w<([^>]+)>/\\U$1/g;
print;
}
")
  )

(defun perl-qw()
  (interactive)
  (insert "qw! fred barney betty wilma dino !
qw/ fred barney betty wilma dino /
qw# fred barney betty wilma dino # # like in a comment!")
  )

(defun perl-shift()
  (interactive)
  (insert "@array = qw# dino fred barney #;
$m = shift(@array); # $m gets \"dino\", @array now has (\"fred\", \"barney\")
$n = shift @array; # $n gets \"fred\", @array now has (\"barney\")
shift @array; # @array is now empty
$o = shift @array; # $o gets undef, @array is still empty
unshift(@array, 5); # @array now has the one-element list (5)
unshift @array, 4; # @array now has (4, 5)
@others = 1..3;
unshift @array, @others; # @array now has (1, 2, 3, 4, 5)")
  )

(defun perl-fileRename()
  (interactive)
  (insert "#!/usr/bin/perl

foreach my $file(glob \"*\")
{
    my $newFile=$file;

    $newFile =~ tr/[A-Z]/[a-z]/; #change upcase letter to low case letter.

    #if new file name is existed.
    if (-e $newFile)
    {
        warn \"The $newFile exists!\\n\";
    }
    else
    {
        rename $file,$newFile
            or
            warn \"Rename $file to $newFile failed:$!\\n\";
    }

    print $newFile.\"\\n\";
}

")
  )

(defun perl-stringReplace()
  (interactive)
  (insert "perl -p -i -e 's/oldstring/newstring/g' `find ./ -name *.html`")
  )

(defun linux-cscope()
  (interactive)
  (insert "find . -name \"*.[cChHsS]\">cscope.out")
  )
   
(defun linux-openssh()
  (interactive)
  (insert "export CC=/c/openwrt/openwrt-na9xx-r25875-20120920/staging_dir/toolchain-mipsel_r2_gcclang-linaro_uClibclang-0.9.32/bin/mipsel-openwrt-linux-uclibclang-gcc

#zlib
./configure --prefix=/path/to/output

#cross compile openssl
$ cd  /work/ssh/source/openssl-0.9.8e
$ ./Configure --prefix=/work/ssh/install/openssl-0.9.8e  os/compiler:arm-none-linux-gnueabi-gcc

#with
$./configure --with-libs --with-zlib=/c/openwrt/software/zip/ --with-ssl-dir=/c/openwrt/software/openssl-0.9.8e/ --host=arm-none-linux-gnueabi
")
  )

(defun linux-openvpn()
  (interactive)
  (insert "export CC=/c/openwrt/openwrt-na9xx-r25875-20120920/staging_dir/toolchain-mipsel_r2_gcclang-linaro_uClibclang-0.9.32/bin/mipsel-openwrt-linux-uclibclang-gcc

#download lzo
$wget http://www.oberhumer.com/opensource/lzo/download/lzo-2.06.tar.gz
$./configure --host=arm-none-linux-gnueabi --prefix=/c/openwrt/software/lzo-2.06
$make && make install


# edit configure file add these line to button
CPPFLAGS=\"$CPPFLAGS -I/c/openwrt/software/lzo-2.06/include/ -I/c/openwrt/software/openssl-0.9.8e/include/ -I/c/openwrt/software/zip/include\"
LDFLAGS=\"$LDFLAGS -L/c/openwrt/software/lzo-2.06/lib/ -L/c/openwrt/software/openssl-0.9.8e/lib/ -L/c/openwrt/software/zip/lib\"

./configure --host=arm-none-linux-gnueabi --disable-plugin-auth-pam
make && make install

how to run 
1. both client and server should have same ca.crt server.crt and so on
2. disable ta.key , if enable \"ta.key 0\" in server. \"ta.key 1\" in client.
3. openvpn client1.key 

run command in server 'openvpn --config /path/to/server.conf'
run command in client 'openvpn --config /path/to/client.conf'
check output console to check.
")
  )

(defun linux-openwrt()
  (interactive)
  (insert "

$make menuconfig

#Tool Chain in build_stage

$make V=99

* dhcp for openwrt
* rtc for openwrt(real time clock)

$ make kernel_menuconfig
    [*] Enable FPU emulation

Disable Telenet

$$$$install openwrt in PC:

/etc/passwd


")
  )

(defun linux-openwrt-3g()
  (interactive)
  (insert "add following kernel module

/dev/ttyUSB0

in /etc/config/network

option device /dev/ttyUSB0
option proto  3g
option apn    dodolns1

in /etc/chatscripts/3g.chat

OK \"ATD*99#\"
")
  )

(defun linux-openwrt-rtc()
  (interactive)
  (insert "it is very important")
  )

(defun linux-openwrt-checklist()
  (interactive)
  (insert "1. rtc
2. bash test
3. 3g modem configuration
")
  )

(defun linux-na910()
  (interactive)
  (insert "3.1 Unpack source code
#tar jxvf opewrt-na910-r2857-yyyymmdd.tar.bz2
# cd openwrt-na910-r25875-yyyymmdd
3.2 Install the packages from the external feeds
#./scripts/feeds update -a
#./scripts/feeds install -a
3.3 Create a default configuration
#make defconfig
3.4 Customize configuration with menuconfig
#make menuconfig")
  )

(defun linux-lockfile()
  (interactive)
  (insert "#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
  int file_desc;
  int save_errno;
  file_desc = open(\"/tmp/LCK.test\", O_RDWR | O_CREAT | O_EXCL, 0444);
  if (file_desc == -1) {
    save_errno = errno;
    printf(\"Open failed with error %d\\n\", save_errno);
  }
  else {
    printf(\"Open succeeded\\n\");
  }
  exit(EXIT_SUCCESS);
}")
  )


(defun linux-getline()
  (interactive)
  (insert "#include<stdio.h>
#include<sys/types.h>
int main(int argc, char *argv[])
{
  char *line = NULL;
  size_t size = 0;
  ssize_t ret;

  while((ret = getline(&line, &size,stdin)) !=  -1)
    printf(\"(%lu) %s\",size,line);
  
  return 0;
}
")
  )

(defun clang-strcpy()
  (interactive)
  (insert "#include <stdio.h>
#include <string.h>

int main()
{
   char src[40];
   char dest[100];
  
   memset(dest, '\\0', sizeof(dest));
   strcpy(src, \"This is tutorialspoint.com\");
   strcpy(dest, src);

   printf(\"Final copied string : %s\\n\", dest);
   
   return(0);
}")
  )

(defun clang-fopen()
  (interactive)
  (insert "FILE *input_file=NULL;
    if (input_file == 0)
    {
	input_file = fopen(input_file_name, \"r\");
	if (input_file == 0)
	    open_error(input_file_name);
    }
")
  )

(defun clang-strcmp()
  (interactive)
  (insert "#include <stdio.h>
#include <string.h>

int main ()
{
   char str1[15];
   char str2[15];
   int ret;


   strcpy(str1, \"abcdef\");
   strcpy(str2, \"ABCDEF\");

   ret = strcmp(str1, str2);

   if(ret > 0)
   {
      printf(\"str1 is less than str2\");
   }
   else if(ret < 0) 
   {
      printf(\"str2 is less than str1\");
   }
   else 
   {
      printf(\"str1 is equal to str2\");
   }
   
   return(0);
}")
  )

(defun clang-printf()
  ""
  (interactive)
  (insert "")
  )


(defun opengl-png()
  (interactive)
  (insert "#ifdef _WIN32
#include <GL/glut.h>
#else
#include <GLUT/glut.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <png.h>
#include <iostream>
 
GLubyte *textureImage;
float rotateX = 0;
float rotateY = 0;
 
int mouseX;
int mouseY;
 
bool loadPngImage(char *name, int &outWidth, int &outHeight, bool &outHasAlpha, GLubyte **outData) {
    png_structp png_ptr;
    png_infop info_ptr;
    unsigned int sig_read = 0;
    int color_type, interlace_type;
    FILE *fp;
 
    if ((fp = fopen(name, \"rb\")) == NULL)
        return false;
 
    /* Create and initialize the png_struct
     * with the desired error handler
     * functions.  If you want to use the
     * default stderr and longjump method,
     * you can supply NULL for the last
     * three parameters.  We also supply the
     * the compiler header file version, so
     * that we know if the application
     * was compiled with a compatible version
     * of the library.  REQUIRED
     */
    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
                                     NULL, NULL, NULL);
 
    if (png_ptr == NULL) {
        fclose(fp);
        return false;
    }
 
    /* Allocate/initialize the memory
     * for image information.  REQUIRED. */
    info_ptr = png_create_info_struct(png_ptr);
    if (info_ptr == NULL) {
        fclose(fp);
        png_destroy_read_struct(&png_ptr, NULL, NULL);
        return false;
    }
 
    /* Set error handling if you are
     * using the setjmp/longjmp method
     * (this is the normal method of
     * doing things with libpng).
     * REQUIRED unless you  set up
     * your own error handlers in
     * the png_create_read_struct()
     * earlier.
     */
    if (setjmp(png_jmpbuf(png_ptr))) {
        /* Free all of the memory associated
         * with the png_ptr and info_ptr */
        png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
        fclose(fp);
        /* If we get here, we had a
         * problem reading the file */
        return false;
    }
 
    /* Set up the output control if
     * you are using standard C streams */
    png_init_io(png_ptr, fp);
 
    /* If we have already
     * read some of the signature */
    png_set_sig_bytes(png_ptr, sig_read);
 
    /*
     * If you have enough memory to read
     * in the entire image at once, and
     * you need to specify only
     * transforms that can be controlled
     * with one of the PNG_TRANSFORM_*
     * bits (this presently excludes
     * dithering, filling, setting
     * background, and doing gamma
     * adjustment), then you can read the
     * entire image (including pixels)
     * into the info structure with this
     * call
     *
     * PNG_TRANSFORM_STRIP_16 |
     * PNG_TRANSFORM_PACKING  forces 8 bit
     * PNG_TRANSFORM_EXPAND forces to
     *  expand a palette into RGB
     */
    png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND, NULL);
 
    png_uint_32 width, height;
    int bit_depth;
    png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
                 &interlace_type, NULL, NULL);
    outWidth = width;
    outHeight = height;
 
    unsigned int row_bytes = png_get_rowbytes(png_ptr, info_ptr);
    *outData = (unsigned char*) malloc(row_bytes * outHeight);
 
    png_bytepp row_pointers = png_get_rows(png_ptr, info_ptr);
 
    for (int i = 0; i < outHeight; i++) {
        // note that png is ordered top to
        // bottom, but OpenGL expect it bottom to top
        // so the order or swapped
        memcpy(*outData+(row_bytes * (outHeight-1-i)), row_pointers[i], row_bytes);
    }
 
    /* Clean up after the read,
     * and free any memory allocated */
    png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
 
    /* Close the file */
    fclose(fp);
 
    /* That's it */
    return true;
}
 
void init(void) {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glEnable(GL_DEPTH_TEST);
    // The following two lines enable semi transparent
    glEnable(GL_BLEND);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 
    int width, height;
    bool hasAlpha;
    char filename[] = \"logo.png\";
    bool success = loadPngImage(filename, width, height, hasAlpha, &textureImage);
    if (!success) {
        std::cout << \"Unable to load png file\" << std::endl;
        return;
    }
    std::cout << \"Image loaded \" << width << \" \" << height << \" alpha \" << hasAlpha << std::endl;
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexImage2D(GL_TEXTURE_2D, 0, hasAlpha ? 4 : 3, width,
                 height, 0, hasAlpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE,
                 textureImage);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glEnable(GL_TEXTURE_2D);
    glShadeModel(GL_FLAT);
}
 
void display(void) {
    glLoadIdentity();
    glTranslatef(0.0, 0.0, -3.6);
    glRotatef(rotateX, 0,1,0);
    glRotatef(rotateY, 1,0,0);
 
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glBegin(GL_QUADS);
    glTexCoord2f(0.0, 0.0);
    glVertex3f(-2.0, -1.0, 0.0);
    glTexCoord2f(0.0, 1.0);
    glVertex3f(-2.0, 1.0, 0.0);
    glTexCoord2f(1.0, 1.0);
    glVertex3f(0.0, 1.0, 0.0);
    glTexCoord2f(1.0, 0.0);
    glVertex3f(0.0, -1.0, 0.0);
 
    glEnd();
    glutSwapBuffers();
}
 
void myReshape(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0, 1.0 * (GLfloat) w / (GLfloat) h, 1.0, 30.0);
    glMatrixMode(GL_MODELVIEW);
}
 
void mousePassive(int x, int y){
    mouseX = x;
    mouseY = y;
}
 
void mouseMotion(int x, int y){
    const float SPEED = 2;
 
    rotateX += (mouseX-x)/SPEED;
    rotateY += (mouseY-y)/SPEED;
    mousePassive(x, y);
    glutPostRedisplay();
}
 
int
main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH);
    glutCreateWindow(\"PNG texture\");
    glutMotionFunc(mouseMotion);
    glutPassiveMotionFunc(mousePassive);
    init();
    glutReshapeFunc(myReshape);
    glutDisplayFunc(display);
    std::cout << \"Use mouse drag to rotate.\" << std::endl;
    glutMainLoop();
    return 0;
}")
  )

(defun opengl-polygon()
  (interactive)
  (insert "glColor3f (1.0, 1.0, 1.0);
    glBegin(GL_POLYGON);
        glVertex3f (0.25, 0.25, 0.0);
        glVertex3f (0.75, 0.25, 0.0);
        glVertex3f (0.75, 0.75, 0.0);
        glVertex3f (0.25, 0.75, 0.0);
    glEnd();")
  )

(defun opengl-line()
  (interactive)
  (insert "glLineWidth(3.0);
	glBegin(GL_LINES);
	glVertex3f(2.5f,2.5f,0.0f);
	glVertex3f(2.0f,2.0f,0.0f);
	glEnd();")
  )

(defun opengl-point()
  (interactive)
  (insert "	glColor3f(0.5,0.5,1.0);
	glPointSize(6.0);
	glBegin(GL_POINTS);
	glVertex3f(2.5f,2.5f,0.0f);
	glEnd();")
  )

(defun opengl-main()
  (interactive)
  (opengl-glut)
  )

(defun opengl-glut()
  (interactive)
  (insert "/*
When creating your project, uncheck OWL,
uncheck Class Library, select Static
instead of Dynamic and change the target
model to Console from GUI.
Also link glut.lib to your project once its done.
*/

#include <windows.h>   // Standard Header For Most Programs
#include <gl/gl.h>     // The GL Header File
#include <gl/glut.h>   // The GL Utility Toolkit (Glut) Header

void init ( GLvoid )     // Create Some Everyday Functions
{

	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);				// Black Background
	glClearDepth(1.0f);									// Depth Buffer Setup
	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glEnable ( GL_COLOR_MATERIAL );
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}

void display ( void )   // Create The Display Function
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear Screen And Depth Buffer
	glLoadIdentity();									// Reset The Current Modelview Matrix
	glTranslatef(-1.5f,0.0f,-6.0f);						// Move Left 1.5 Units And Into The Screen 6.0
	glBegin(GL_TRIANGLES);								// Drawing Using Triangles
	glVertex3f( 0.0f, 1.0f, 0.0f);					// Top
	glVertex3f(-1.0f,-1.0f, 0.0f);					// Bottom Left
	glVertex3f( 1.0f,-1.0f, 0.0f);					// Bottom Right
	glEnd();											// Finished Drawing The Triangle
	glTranslatef(3.0f,0.0f,0.0f);						// Move Right 3 Units
	glBegin(GL_QUADS);									// Draw A Quad
	glVertex3f(-1.0f, 1.0f, 0.0f);					// Top Left
	glVertex3f( 1.0f, 1.0f, 0.0f);					// Top Right
	glVertex3f( 1.0f,-1.0f, 0.0f);					// Bottom Right
	glVertex3f(-1.0f,-1.0f, 0.0f);					// Bottom Left
	glEnd();

	glColor3f(1.0,0.0,1.0);
	glLineWidth(3.0);
	glBegin(GL_LINES);
	glVertex3f(2.5f,2.5f,0.0f);
	glVertex3f(2.0f,2.0f,0.0f);
	glEnd();

	glColor3f(0.5,0.5,1.0);
	glPointSize(6.0);
	glBegin(GL_POINTS);
	glVertex3f(2.5f,2.5f,0.0f);
	glEnd();

	glColor3f(1.0,1.0,1.0);

	glutSwapBuffers ( );
        //glFlush();
	// Swap The Buffers To Not Be Left With A Clear Screen
}

void reshape ( int w, int h )   // Create The Reshape Function (the viewport)
{
	glViewport     ( 0, 0, w, h );
	glMatrixMode   ( GL_PROJECTION );  // Select The Projection Matrix
	glLoadIdentity ( );                // Reset The Projection Matrix
	if ( h==0 )  // Calculate The Aspect Ratio Of The Window
		gluPerspective ( 80, ( float ) w, 1.0, 5000.0 );
	else
		gluPerspective ( 80, ( float ) w / ( float ) h, 1.0, 5000.0 );
	glMatrixMode   ( GL_MODELVIEW );  // Select The Model View Matrix
	glLoadIdentity ( );    // Reset The Model View Matrix
}

void keyboard ( unsigned char key, int x, int y )  // Create Keyboard Function
{
	switch ( key ) {
	case 27:        // When Escape Is Pressed...
		exit ( 0 );   // Exit The Program
		break;        // Ready For Next Case
	default:        // Now Wrap It Up
		break;
	}
}

void arrow_keys ( int a_keys, int x, int y )  // Create Special Function (required for arrow keys)
{
	switch ( a_keys ) {
	case GLUT_KEY_UP:     // When Up Arrow Is Pressed...
		glutFullScreen ( ); // Go Into Full Screen Mode
		break;
	case GLUT_KEY_DOWN:               // When Down Arrow Is Pressed...
		glutReshapeWindow ( 500, 500 ); // Go Into A 500 By 500 Window
		break;
	default:
		break;
	}
}

void main ( int argc, char** argv )   // Create Main Function For Bringing It All Together
{
	glutInit            ( &argc, argv ); // Erm Just Write It =)
	init ();
	glutInitDisplayMode ( GLUT_RGB | GLUT_DOUBLE ); // Display Mode
	glutInitWindowSize  ( 500, 500 ); // If glutFullScreen wasn't called this is the window size
	glutCreateWindow    ( \"NeHe's OpenGL Framework\" ); // Window Title (argv[0] for current directory as title)
	glutDisplayFunc     ( display );  // Matching Earlier Functions To Their Counterparts
	glutReshapeFunc     ( reshape );
	glutKeyboardFunc    ( keyboard );
	glutSpecialFunc     ( arrow_keys );
	glutMainLoop        ( );          // Initialize The Main Loop
}
")
  )

(defun opengl-version()
  (interactive)
  (insert "#include <stdio.h>
#include <GL/glut.h>

int main(int argc, char** argv)
{
  glutInit(&argc,argv);

  glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);

  glutInitWindowSize(300,300);

  glutInitWindowPosition(100,100);

  glutCreateWindow(\"OpenGL Version\");
  const GLubyte* name = glGetString(GL_VENDOR); 
  const GLubyte* biaoshifu = glGetString(GL_RENDERER); 
  const GLubyte* OpenGLVersion =glGetString(GL_VERSION); 
  const GLubyte* gluVersion= gluGetString(GLU_VERSION); 
  printf(\"OpenGL manufactory' name：%s\\n\", name);
  printf(\"shader：%s\\n\", biaoshifu);
  printf(\"OOpenGL version：%s\\n\",OpenGLVersion );
  printf(\"OGLU version：%s\\n\", gluVersion);
  
  return 0;
}
")
  )

(defun opengl-glTranslatef()
  (interactive)
  (insert "glTranslatef(-1.5f,0.0f,-6.0f);")
  )

(defun opengl-glRotated()
  (interactive)
  (insert "glRotated(60,1,0,0);")
  )

(defun opengl-matrix()
  (interactive)
  (insert "glPushMatrix();  
        glTranslated(-2.4,-1.2,-6);  
        glRotated(60,1,0,0);  
        glRotated(a,0,0,1);  
        glutWireSphere(1,slices,stacks);  
    glPopMatrix(); ")
  )

(defun opengl-glOrtho()
  (interactive)
  (insert "//glOrtho(left, right, bottom, top, near, far);
//left coordinate,right coordinate,bottom coordinate, coordinate

void reshape(int width , int height)
{
    glViewport(width, height); 
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (width <= height)
        glOrtho(-1.5, 1.5, -1.5 * (GLfloat)height/(GLfloat)width, 1.5 * (GLfloat)height/(GLfloat)width, -10.0, 10.0);
    else
        glOrtho(-1.5*(GLfloat)width/(GLfloat)height, 1.5*(GLfloat)w/(GLfloat)h, -1.5, 1.5, -10.0, 10.0);
    ....
}
")
  )

(defun opengl-glScalef()
  (interactive)
  (insert "glScalef (1.0, 2.0, 1.0); // enlarge 2 along y coordinate")
  )

(defun opengl-timer()
  (interactive)
  (insert "
#define TimeInterval 330
glutTimerFunc(TimeInterval, TimerFunction, 1);

void TimerFunction(int value)
{


    glutPostRedisplay();
    #define TimeInterval 330
    glutTimerFunc(TimeInterval,TimerFunction, 1);
}
")
  )

(defun linux-fwrite-emptyfile()
  (interactive)
  (insert "#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int size = 661215; 

int main(int argc,char **argv)
{
  char a[48];
  char b[1000];  
  FILE * pFile;
  int i,j;
    
  memset(a,0,48*sizeof(char));
  memset(b,0,1000*sizeof(char));  
  strcpy(a,\"SMIF...\");

  pFile = fopen (\"myfile.bin\", \"wb\");
  fwrite (a , sizeof(char), 48, pFile);

  for(i = 0;i<size/1000;i++)
    {
      fwrite(b,sizeof(char),1000,pFile);
    }

  fwrite(b,sizeof(char),size%1000,pFile);

  fclose(pFile);
  

  return 0;
}
")
  )

(defun linux-random()
  (interactive)
  (insert "	int i;
	time_t t;
	srand((unsigned) time(&t));
	printf(\"Ten random numbers from 0 to 99\\n\\n\");
	for(i=0; i<10; i++)
		printf(\"%d\\n\", rand() % 100);
	return 0;
")
  )

(defun perl-sub(&optional subName)
  (interactive)
  (or subName (setq subName (read-from-minibuffer "Enter subName Name: ")))
  (insert (format "sub %s
{
  $def + $abc
  //last statement is return value;
}


$def = 1
$abc = 2
$returnValue = %s" subName subName))
  )

(defun linux-vsftp()
  (interactive)
  (insert "#/etc/vsftp/vsftpd.conf

# anonymous path is \"anon_root = path \"

")
  )

(defun linux-tgz()
  (interactive)
  (insert "#gzip -d file.tgz

#tar xvf file.tar -C /path/to/output/")
  )

(defun linux-tar()
  (interactive)
  (insert "$tar cvf file.tar folder1/ folder2/

$tar xvf file.tar -C /path/to/output/")
  )

(defun linux-autotool()
  (interactive)
  (insert "$autoscan
$mv configure.scan configure.ac
$autoconf

$mv Makefile Makefile.in
$./configure

-------------------------------
$autoheader
### in config.h
#define HAVE_GETTIMEOFDAY 1

<code>
#include <stdio.h>
#include \"config.h\"
 
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#include <time.h>
#endif
 
double get_sec_since_epoch()
{
   double sec;
 
   #ifdef HAVE_GETTIMEOFDAY
      struct timeval tv;
 
      gettimeofday(&tv, NULL);
      sec = tv.tv_sec;
      sec += tv.tv_usec / 1000000.0;
   #else
      sec = time(NULL);
   #endif
 
   return sec;
}
 
int main(int argc, char* argv[])
{
   printf(\"%f\\n\", get_sec_since_epoch());
 
   return 0;
}
</code>
$ autoscan
")
  )

(defun linux-debugbreak()
  (interactive)
  (insert "//linux
#define BREAK_HERE raise(SIGINT)

#define EMBED_BREAKPOINT  asm volatile (\"int3;\")
")
  )

(defun linux-backtrace()
  (interactive)
  (insert "
 -rdynamic

(gdb) list *0x804d5ce
addr2line -e finite_element 0x804d5ce

#include <stdio.h>
#include <signal.h>
#include <stdio.h>
#include <signal.h>
#include <execinfo.h>

void bt_sighandler(int sig, struct sigcontext ctx) {

  void *trace[16];
  char **messages = (char **)NULL;
  int i, trace_size = 0;

  if (sig == SIGSEGV)
    printf(\"Got signal %d, faulty address is %p, \"
           \"from %p\\n\", sig, ctx.cr2, ctx.eip);
  else
    printf(\"Got signal %d\\n\", sig);

  trace_size = backtrace(trace, 16);
  /* overwrite sigaction with caller's address */
  trace[1] = (void *)ctx.eip;
  messages = backtrace_symbols(trace, trace_size);
  /* skip first stack frame (points here) */
  printf(\"[bt] Execution path:\\n\");
  for (i=1; i<trace_size; ++i)
  {
    printf(\"[bt] #%d %s\\n\", i, messages[i]);

    char syscom[256];
    sprintf(syscom,\"addr2line %p -e backtraceTest\", trace[i]); //last parameter is the name of this app
    system(syscom);
  }

  exit(0);
}


int func_a(int a, char b) {

  char *p = (char *)0xdeadbeef;

  a = a + b;
  *p = 10;  /* CRASH here!! */

  return 2*a;
}


int func_b() {

  int res, a = 5;

  res = 5 + func_a(a, 't');

  return res;
}


int main() {

  /* Install our signal handler */
  struct sigaction sa;

  sa.sa_handler = (void *)bt_sighandler;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = SA_RESTART;

  sigaction(SIGSEGV, &sa, NULL);
  sigaction(SIGUSR1, &sa, NULL);
  /* ... add any other signal here */

  /* Do something */
  printf(\"%d\\n\", func_b());
}

")
  )

(defun linux-gdb()
  (interactive)
  (insert "set follow-fork-mode mode
    Set the debugger response to a program call of fork or vfork. A call to fork or vfork creates a new process. The mode can be:

    parent
        The original process is debugged after a fork. The child process runs unimpeded. This is the default.

    child
        The new process is debugged after a fork. The parent process runs unimpeded.

    ask
        The debugger will ask for one of the above choices. 

show follow-fork-mode ")
  )

(defun linux-debugkernel()
  (interactive)
  (insert "linux/kernel.h
dump_stack();

save_stack_trace()
dump_trace()
")
  )

(defun linux-debug()
  (interactive)
  (insert "
#ifdef DEBUG
#define F_OUT printf(\"%s:\", __FUNCTION__);fflush(stdout);
#define L_OUT printf(\"%s:%d:\", __FILE__, __LINE__);fflush(stdout);
#define A_OUT printf(\"%s:%d:%s:\", __FILE__, __LINE__, __FUNCTION__);fflush(stdout);
#define D_OUT printf(\"DEBUG:\");fflush(stdout);

#define F_PRINTF(fmt, arg...) F_OUT printf(fmt, ##arg)
#define L_PRINTF(fmt, arg...) L_OUT printf(fmt, ##arg)
#define A_PRINTF(fmt, arg...) A_OUT printf(fmt, ##arg)
#define PRINTF(fmt, arg...) D_OUT printf(fmt, ##arg)
#define DBUG(a) {a;}
#else
#define F_OUT
#define L_OUT
#define A_OUT
#define D_OUT

#define F_PRINTF(fmt, arg...)
#define L_PRINTF(fmt, arg...)
#define A_PRINTF(fmt, arg...)
#define PRINTF(fmt, arg...)
#define DBUG(a)
#endif

#define F_PERROR(fmt) F_OUT perror(fmt)
#define L_PERROR(fmt) L_OUT perror(fmt)
#define A_PERROR(fmt) A_OUT perror(fmt)
#define PERROR(fmt) D_OUT perror(fmt)")
  )

(defun linux-grep-find()
  (interactive)
  (insert "find . -type f | xargs grep '\.\.\.'")
  )

(defun linux-grep(&optional String)
  (interactive)
  ;; &optional String
  (or String (setq String (read-from-minibuffer "Enter String Name: ")))
  (insert (format "grep -r '%s' *" String)
          )
  )

(defun linux-find()
  (interactive)
  (insert "find . -maxdepth 1 -type f | xargs fgrep '...'")
  )

(defun linux-mount()
  (interactive)
  (insert "mount -t iso9660 -o ro /dev/cdrom /cdrom")
  )

(defun linux-alias()
  (interactive)
  (insert "alias

~/.bashrc
")
  )

(defun linux-openvpn()
  (interactive)
  (insert "
dev tap0
proto tcp
server-bridge  192.168.88.1 255.255.255.0 192.168.88.150 192.168.88.200
management localhost 7505
ca /root/openvpn/conf/ca.crt
cert /root/openvpn/conf/server.crt
key /root/openvpn/conf/server.key
dh /root/openvpn/conf/dh1024.pem
keepalive 10 120
push \"redirect-gateway\"

")
  )

(defun svn-editor()
  (interactive)
  (insert "set editor=/path/to/emacsclientw.exe")
  )

(defun linux-bochs-disassemble()
  (interactive)
  (insert "typedef unsigned char Bit8u;

static disassembler bx_disassemble;
Bit8u  instr_buf[16];
char   char_buf[512];

unsigned isize = bx_disassemble.disasm(0,0,0,0,instr_buf,char_buf+i);")
  )

(defun linux-rs232()
  (interactive)
  (insert "
RTS(Request To Send)
CTS(Clear To Send)

")
  )

(defun linux-svn-gnome()
  (interactive)
  (insert "~/.subversion/config

[auth]
password-stores \=
")
  )

(defun linux-svn-AddUserNameAndPassword()
  ""
  (interactive)
  (insert "
svnroot is svn's repo path
/root/svnroot/conf/passwd")
  )

(defun linux-svn-http-timeout()
  ""
  (interactive)
  (insert "~/.subversion/servers

[global]
http-timeout = 6000
")
  )

(defun linux-folder-size()
  ""
  (interactive)
  (insert "du -sh folderName")
  )

(defun fedora-firewalld()
  ""
  (interactive)
  (insert "# Fedora 20
service firewalld start
firewall-cmd --zone=public --add-port=80/tcp

")
  )

(defun fedora-iptables()
  ""
  (interactive)
  (insert "iptables -I input -s 1.1.1.1 -j drop

iptables -L
iptables --flush


service iptables save


")

  )

(defun linux-gpio()
  (interactive)
  (insert "#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

//Device Drivers  ---> GPIO Support  ---> /sys/class/gpio/... (sysfs interface)

sprintf(buf, \"/sys/class/gpio/gpio%d/value\", gpio);

fd = open(buf, O_WRONLY);

// Set GPIO high status
write(fd, \"1\", 1); 
// Set GPIO low status 
write(fd, \"0\", 1); 

close(fd);

lseek(fd, 0, SEEK_SET);
")
  )

(defun openwrt-openvpn()
  ""
  (interactive)
  (insert "")
  )

(defun openwrt-3gmodem()
  (interactive)
  (insert "\"/etc/config/network\":

config 'interface' 'wan'
	option 'proto' '3g'
	option 'service' 'umts'
	option 'device' '/dev/ttyUSB0'
	option 'apn' 'internet'
	option 'pincode' ''
	option 'username' ''
	option 'password' ''
")
  )

(defun apache-conf()
  ""
  (interactive)
  (insert "DocumentRoot \"c:/www\"]
# after modified DocumentRoot folder, Directory section is need to changed as well
<Directory \"c:/www\">
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
")
  )
(defun linux-printk()
  ""
  (interactive)
  (insert "printk, dmesg, /var/log/messages")
  )

(defun linux-shutdown()
  "shutdown linux in 180 minutes"
  (interactive)
  (insert "shutdown -h +180")
  )

(defun fedora-lamp()
  "fedora install linux apache mysql php"
  (interactive)
  (insert "sudo yum install httpd
sudo service httpd start

;;install 'mysql' and 'mysql-server'
sudo yum install mysql mysql-server
sudo service mysqld start

;; install 'php' and 'php-mysql'
sudo yum install php php-mysql
")
  )